package com.mlc.wx.controller.frontend;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.mlc.common.core.controller.BaseController;
import com.mlc.common.core.domain.AjaxResult;
import com.mlc.common.utils.StringUtils;
import com.mlc.wx.controller.frontend.vo.WeChatUserInfo;
import com.mlc.wx.domain.User;
import com.mlc.wx.service.IUserService;
import com.mlc.wx.utils.WeChatUtil;
import org.aspectj.weaver.loadtime.Aj;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/frontend/wx")
public class WXLoginController extends BaseController {
    @Autowired
    private IUserService userService;
    @Autowired
    private WeChatUtil weChatUtil;

    @PostMapping("/login")
    public AjaxResult login(@RequestBody WeChatUserInfo userInfo){
        JSONObject jsonObject = weChatUtil.getSessionKeyOrOpenId(userInfo.getCode());
        String openId = (String) jsonObject.get("openid");
        //1、通过openId 查询用户
        User user = userService.selectUserByOpenId(openId);

        //2、判断用户是否为空
        if (StringUtils.isNull(user)){
            //2.1、为空，新增用户
            insertUser(openId, userInfo);
            //2.2、重新查询用户信息，并返回给前端
            user = userService.selectUserByOpenId(openId);
            return AjaxResult.success(user);
        }

        //3、判断用户状态
        if (user.getStatus() == 0){

            //新增完成后重新查询用户信息
            return AjaxResult.error("用户已被禁用");
        }


        return AjaxResult.success(user);
    }

    private Integer insertUser(String openId, WeChatUserInfo userInfo){
        JSONObject jsonUserInfo = JSONUtil.parseObj(userInfo.getRawData());
        Integer gender = (Integer) jsonUserInfo.get("gender");
        String photo = (String) jsonUserInfo.get("avatarUrl");
        String nickname = (String) jsonUserInfo.get("nickName");

        User userDomain = new User(openId, nickname, photo, gender,nickname);
        System.out.println("gender = " + gender + " ；photo = " + photo + " ；nickname = " + nickname);

        //不存在则新增用户
        return userService.insertUser(userDomain);
    }

}
